// 所有关于购物车的接口
var express = require("express");
var router = express.Router();
var mongo = require("./db");
var mongodb = require("mongodb");
var ObjectId = mongodb.ObjectId;
var myToken = require("./myToken");
const { listen } = require("../app");
// 添加购物车接口
router.post("/addCart", function (req, res) {

  myToken.verify(req.body.token, function (err, data) {
    if (data) { //验证token 为真已登录

      var obj = {
        uid: req.body.uid,  //用户id
        num: req.body.num, //数量
        pname: req.body.pname,
        price: req.body.price,
        pid: req.body.pid,  //商品id 
        des: req.body.des,
        img: req.body.img,
        inventory: req.body.inventory,
        oldpirce: req.body.oldprice,
        ischeck: "true",//商品是否被选中
        date: new Date().getTime()
      }
      mongo("find", "cartlist", { pid: req.body.pid, uid: req.body.uid }, function (mydata) {
        if (mydata.length == 0) {  //未查询到当前商品已添加
          mongo("insert", "cartlist", obj, function (data) {
            res.send({ success: "添加购物车成功" })
          })
        } else { //查询到当前商品已添加
          var num = Number(mydata[0].num) + Number(req.body.num)
          mongo("update", "cartlist", [{ pid: req.body.pid, uid: req.body.uid }, { num: num.toString() }], function () {
            res.send({ success: "添加成功" })
          })
        }
      })
    } else { //验证token为false  未登录
      res.send({ err: "请登录！！" })
    }
  })
})
// 获取购物车列表接口
router.post("/cartAll", function (req, res) {
  myToken.verify(req.body.token, function (err, data) {
    if (data) {
      mongo("find", "cartlist", { uid: req.body.uid }, function (data) {
        res.send(data)
      })
    } else {
      res.send({ err: '请先登录' })
    }
  })

})
// 删除购物车接口
router.post("/delCart", function (req, res) {
  mongo("del", "cartlist", { _id: ObjectId(req.body.id) }, function () {
    res.send({ success: "删除成功" })
  })
})

// 更改数量的接口
router.post("/updateNum", function (req, res) {
  mongo("update", "cartlist", [{ _id: ObjectId(req.body.id) }, { num: req.body.num }], function () {
    res.send({ success: "更新数量成功" })
  })
})
// 单选接口
router.post("/check", function (req, res) {
  mongo("update", "cartlist", [{ _id: ObjectId(req.body.id) }, { ischeck: req.body.ischeck }], function () {
    res.send({ success: "操作成功" })
  })
})
// 全选接口
router.post("/allCheck", function (req, res) {
  mongo("find", "cartlist", { uid: req.body.uid }, function (data) { //查询到所有数据
    console.log(data)
    for (var i = 0; i < data.length; i++) { //循环修改每条数据
      mongo("update", "cartlist", [{ _id: data[i]._id }, { ischeck: req.body.allCheck }], function () {

      })
      if (i == data.length - 1) {
        res.send({ success: "操作成功" })
      }
    }
  })
})





module.exports = router;